package com.applancer.form;

import java.util.ArrayList;

import android.widget.TextView;

import com.applancer.provider.StringUtils;

public class CharacterField implements IValidator {
	// The underlying control this field is representing
	private TextView control;
	// Because whether required or not is so essential
	// give it a special status.
	private boolean required = true;

	// A list of value validators to be attached
	private ArrayList<IValueValidator> valueValidatorList = new ArrayList<IValueValidator>();

	public CharacterField(TextView tv) {
		this(tv, true);
	}

	public CharacterField(TextView tv, boolean inRequired) {
		control = tv;
		required = inRequired;
	}

	@Override
	public boolean validate() {
		String value = getValue();
		if (StringUtils.invalidString(value)) {
			// invalid string
			if (required) {
				warnRequiredField();
				return false;
			}
		}

		if (!StringUtils.acceptString(value)) {
			// invalid string
			if (required) {
				warnAcceptField();
				return false;
			}
		}

		for (IValueValidator validator : valueValidatorList) {
			boolean result = validator.validateValue(getValue());
			if (result == true)
				continue;
			if (result == false) {
				String errorMessage = validator.getErrorMessage();
				setErrorMessage(errorMessage);
				return false;
			}
		}
		return true;
	}

	private void warnAcceptField() {
		setErrorMessage("Field only accept a-z, A-Z, 0-9");
	}

	private void warnRequiredField() {
		setErrorMessage("This is a required field");
	}

	public void setErrorMessage(String message) {
		control.setError(message);
	}

	public String getValue() {
		return this.control.getText().toString();
	}
}
